import {dateFormat} from "../../utils/util";

const WXAPI = require('apifm-wxapi')
const AUTH = require('../../utils/auth')
const wxpay = require('../../utils/pay.js')
const util = require('../../utils/util')
const CONFIG = require('../../config.js')
const SHOP = require('../../utils/shop')
import Dialog from '@vant/weapp/dialog/dialog';
const APP = getApp()
APP.configLoadOK = () => {

}

Page({
  data: {
    mainActiveIndex:0,
    timeSelector:[
    ],
    day:0,
    wxlogin: true,
    switch1 : true, //switch开关
    groupWay:"joinGroup",
    addressList: [],
    curAddressData: null,
    distance: '',
    totalScoreToPay: 0,
    goodsList: [],
    timeOptions:[],
    allGoodsPrice: 0,
    amountReal: 0,
    yunPrice: 0,
    deliveryFeeEstimate:0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    pingtuanOpenId: undefined, //拼团的话记录团号
    selectedGroup:0,
    shareGroupId:0,
    shareGroup:{},
    takeTime:'',
    curCoupon: null, // 当前选择使用的优惠券
    curCouponShowText: '请选择使用优惠券', // 当前选择使用的优惠券
    peisongType: 'kd', // 配送方式 kd,zq 分别表示快递/到店自取
    submitLoding: false,
    remark: '',
    launchGroup:false,
    groupIndex:[],
    joinGroupId:0,
    groupName:'',
    groups:[],
    account:{},
    wxPayAmount:0,
    currentDate: new Date().getHours() + ':' + (new Date().getMinutes() % 10 === 0 ? new Date().getMinutes() : Math.ceil(new Date().getMinutes() / 10) * 10),
    minHour: new Date().getHours(),
    minMinute: new Date().getMinutes(),
    formatter(type, value) {
      if (type === 'hour') {
        return `${value}点`;
      } else if (type === 'minute') {
        return `${value}分`;
      }
      return value;
    },
    filter(type, options) {
      if (type === 'minute') {
        return options.filter((option) => option % 10 === 0);
      }
      return options;
    },
  },
  diningTimeChange(a) {
     
    const selectedHour = a.detail.getColumnValue(0).replace('点', '') * 1

    if (selectedHour == new Date().getHours()) {
      let minMinute = new Date().getMinutes()
      if (minMinute % 10 !== 0) {
        minMinute = minMinute / 10 + 1
      }
      this.setData({
        minMinute
      })
    } else {
      this.setData({
        minMinute: 0
      })
    }
  },
  onShow(){
    AUTH.checkHasLogined()
    SHOP.checkShop()
    this.setData({
      shopInfo: wx.getStorageSync('shopInfo'),
      peisongType: wx.getStorageSync('peisongType')
    })
    AUTH.checkHasLogined().then(isLogined => {
      this.setData({
        wxlogin: isLogined
      })
      if (isLogined) {
         this.doneShow()
       
      }
    })
    AUTH.wxaCode().then(code => {
      this.data.code = code
    })
  },
  getBreakfirstOptions(date){
    const now = new Date()
    const today = util.dateFormat("yyyy-MM-dd",now)
    const d = util.dateFormat("yyyy-MM-dd",date)
    if(d===today){
      return []
    }
    return util.getTimeRangeList("08:00","10:00",10)
  },
  getTimeOptions(date,takeTime){
  
    const now = new Date()
    const today = util.dateFormat("yyyy-MM-dd",now)
    const d = util.dateFormat("yyyy-MM-dd",date)
    
   const lunch = util.getTimeRangeList("11:00","12:30",10)
   const dinner = util.getTimeRangeList("18:00","20:30",10)
   if (d === today){
      // 10:00以后
      const time = dateFormat("HHmm",date)
     if (time > 1000 && time< 1700){
       return dinner
     }
      if(time > 1700){
       return []
     }
   }
   return [...lunch,...dinner]
 },
  initMinPickTime(){
   
    const {shopFreeTimes ,usedGroupTime} = this.data.curAddressData
    const times = shopFreeTimes.map(v=>{return v.takeTime});
    const shop = this.data.shopInfo

   const now =new Date()
    const timeSelector = []
    const daySimplify = ["今天",'明天','后天','','']
    for (let i=0;i<5;i++){
      const first =  util.getDayCN(now)
    let list = []
      if(shop.isBreakfast){
        list = this.getBreakfirstOptions(now)
        
      }else{
        list = this.getTimeOptions(now)
      }
      const dateStr = util.dateFormat('yyyy-MM-dd ',now)
      const dateStrSimple = util.dateFormat('MM-dd ',now)
      const children1 = list.map(v=>{
      
        const index =  usedGroupTime.indexOf(dateStr + v)
        var free = false
        var exists = false
       
        if(times.indexOf(v) !=-1 && this.data.launchGroup){
          free = true
            if(index != -1){
              exists = true
            }
        }
        return {text:v,free,exists}
      })
      const children = []
      if(list.length > 0){
       let  relative = daySimplify[i]
       if(!relative){
          relative = dateStrSimple
       }
        timeSelector.push({
          text: relative +  "(" + first +")",
          date:dateStr,
          children,
          children1
        })
      }
      const date = now.getDate()
      now.setDate(date +1)
    }
   const mainActiveIndex = this.data.mainActiveIndex
    const timeOptions = timeSelector[mainActiveIndex].children1
    
    this.setData({timeSelector,timeOptions})
  },
  selectTime(e){
    const time  = e.currentTarget.dataset.time.text
    const mainOption = this.data.timeSelector[this.data.mainActiveIndex]
    this.setData({
      diningTime:mainOption.text + ' ' + time,
      takeTime: mainOption.date +  time,
      diningTimeShow: false
    })
    this.createOrder()
  },
  changeDay(e){
    const timeOptions = this.data.timeSelector[e.detail.index].children1
   this.setData({mainActiveIndex:e.detail.index,timeOptions})
  },

  async doneShow() {
    let goodsList = [];
    const token = wx.getStorageSync('token')
    //立即购买下单
    if ("buyNow" == this.data.orderType) {
      goodsList = wx.getStorageSync('pingtuanGoodsList')
    } else {
      //购物车下单
      const res = await WXAPI.shippingCarInfo(token)
      if (res.code == 0) {
        goodsList = res.data.items
      }
    }
    this.setData({
      goodsList: goodsList,
      peisongType: this.data.peisongType,
    })
    
    this.initShippingAddress()
  },
  groupChanged(event){
    let groupIndex = []

    let selected = event.detail
    if(selected.length > 1){
      groupIndex.push( selected.pop())
    }else{
      groupIndex = event.detail
    }

    let updateData = { groupIndex:groupIndex}
    if (groupIndex.length >0 ){
      let group = this.data.groups[groupIndex[0]]
      updateData.diningTime = group.showTakeTime
      updateData.takeTime = group.takeTime
      updateData.joinGroupId = group.id
    }else{
      updateData.joinGroupId = 0
    }
    this.setData(updateData)

    this.createOrder()
  },
  tapClearShareGroup(){
    this.clearShareGroup()
    this.groupNearby()
  },
  clearShareGroup(){
    this.setData({
      shareGroup : {},
      shareGroupId :null
    })
    this.setData({groupIndex:[]})
    wx.removeStorageSync('groupId')

  },
  processLaunchGroup(launch){
    
    let groupName = this.data.groupName
    if(launch ){
      if( !this.data.groupName){
        groupName = this.data.nickname + '的团'
      }
    }
    this.setData({groupName,launchGroup: launch,groupIndex:[]})
    this.processYunfei()
  },
  moreGroups(){
    if(!this.data.curAddressData){
      wx.showToast({
        title: '请先选择配送地址',
        icon:'error'
      })
      return ;
    }
    wx.navigateTo({
      url: "/pages/group-list/index?latitude=" + this.data.curAddressData.latitude + "&longitude=" + this.data.curAddressData.longitude,
    })
  },
  async groupNearby(){
    
    if(this.data.curAddressData){
      let latitude = this.data.curAddressData.latitude
      let longitude = this.data.curAddressData.longitude
      let id = this.data.selectedGroup
   
      const groupRes = await WXAPI.groupNearby({id,latitude,longitude,page:1,pageSize:2});

      if (groupRes.code === 0){
        const groups = groupRes.data
        const groupWay = groups && groups.length >0 ? 'joinGroup' : 'launchGroup'

        if(groupWay === 'launchGroup'){
          // this.processLaunchGroup(true)
        }
        this.setData({
          groups,
          groupWay
        })
       
        if(id >0 ){
          
          groupRes.data.forEach((v,index)=>{

            if (id === v.id){
              this.setData({
                diningTime : v.showTakeTime,
                takeTime:v.takeTime,
                joinGroupId:id,
                groupIndex:[index.toString()]
              })
              this.deliveryFee()
            }
          })
        }
      }
    }
  },
  async onLoad(e) {
    let _data = {}
    if (e.orderType) {
      _data.orderType = e.orderType
    }
    if (e.pingtuanOpenId) {
      _data.pingtuanOpenId = e.pingtuanOpenId
    }
    this.setData(_data)
    await AUTH.checkHasLogined()
    this.getUserApiInfo()
    this.getAccount()
  },
  async getAccount(){
    const res = await WXAPI.userAmount(wx.getStorageSync('token'));
    if(res.code ===0 ){
        
        const account = res.data
        this.setData({account})
    }else{
      wx.showModal({
        title: '错误',
        content: '无法获取用户资金信息',
        showCancel: false
      })
    }
  },
  selected(e){
    const peisongType = e.currentTarget.dataset.pstype
    this.setData({
      peisongType
    })
    wx.setStorageSync('peisongType', peisongType)
    this.createOrder()
  },
  
  getDistrictId: function (obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },
  // 备注
  remarkChange(e){
    this.data.remark = e.detail.value
  },
  goCreateOrder(){
    if (this.data.submitLoding) return
    const mobile = this.data.mobile
    if (this.data.peisongType == 'zq' && !mobile) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      })
      return
    }
    if (this.data.groupWay === 'joinGroup' && !this.data.joinGroupId) {
      wx.showToast({
        title: '未选择参加的团',
        icon: 'none'
      })
      return
    }
    if (!this.data.diningTime) {
      wx.showToast({
        title: '请选择自取/配送时间',
        icon: 'none'
      })
      return
    }
  
   
    if (this.data.shopInfo.serviceDistance  && this.data.distance && this.data.distance > this.data.shopInfo.serviceDistance * 1000 && this.data.peisongType == 'kd') {
      wx.showToast({
        title: '当前地址超出配送范围',
        icon: 'none'
      })
      return
    }
   
    if (!this.data.curAddressData) {
      wx.showToast({
        title: '请选收货人',
        icon: 'none'
      })
      return
    }
    this.setData({
      submitLoding: true
    })
    const subscribe_ids = wx.getStorageSync('subscribe_ids')

    if (subscribe_ids) {
      wx.requestSubscribeMessage({
        tmplIds: subscribe_ids.split(','),
        success(res) {},
        fail(e) {
          this.setData({
            submitLoding: false
          })
          console.error(e)
        },
        complete: (e) => {
          this.createOrder(true)
        },
      })
    } else {
      this.createOrder(true)
    }
  },
  onChangeGroupWay(event){

    const {index,name,title} = event.detail
    var launchGroup = false
    const groupWay = name;
    this.setData({launchGroup,groupWay})

    if (name === 'launchGroup'){
      launchGroup = true
      this.processLaunchGroup(true)
      this.setData({groupIndex:[],joinGroupId:0})
    }else if(name === 'joinGroup'){
      this.processLaunchGroup(false)
    }else{
      
      this.processLaunchGroup(false)
      this.setData({groupIndex:[],joinGroupId:0})
    }
   
    if(this.data.takeTime && name != 'joinGroup'){
      this.createOrder()
    }
   
  },
  processJoinGroup(){},

  createOrder: function (e) {
    
    var that = this;
    var loginToken = wx.getStorageSync('token') // 用户登录 token
    var remark = this.data.remark; // 备注信息
    const postData = {
      token: loginToken,
      goodsJsonStr: that.data.goodsJsonStr,
      remark: remark,
      peisongType: that.data.peisongType,
      launchGroup:this.data.launchGroup,
      isCanHx: true
    }

    if (this.data.shopInfo) {
      postData.shopIdZt = this.data.shopInfo.id
      postData.shopNameZt = this.data.shopInfo.name
    }
    postData.groupId =this.data.joinGroupId
    if (that.data.kjId) {
      postData.kjid = that.data.kjId
    }
    if (that.data.pingtuanOpenId) {
      postData.pingtuanOpenId = that.data.pingtuanOpenId
    }
    const extJsonStr = {}
    if (postData.peisongType == 'zq') {
      extJsonStr['联系电话'] = this.data.mobile
      extJsonStr['取餐时间'] = this.data.diningTime
    } else {
      postData.addressId = that.data.curAddressData.id
      extJsonStr['送达时间'] = this.data.diningTime
    }
    postData.extJsonStr = JSON.stringify(extJsonStr)
    postData.takeTime = that.data.takeTime
    if (e && postData.peisongType == 'kd') {
      if (!that.data.curAddressData) {
        wx.hideLoading();
        wx.showToast({
          title: '请设置收货地址',
          icon: 'none'
        })
        return;
      }

      
      if (postData.peisongType == 'kd') {
        postData.provinceId = that.data.curAddressData.provinceId;
        postData.cityId = that.data.curAddressData.cityId;
        if (that.data.curAddressData.districtId) {
          postData.districtId = that.data.curAddressData.districtId;
        }
        postData.address = that.data.curAddressData.address;
        postData.linkMan = that.data.curAddressData.linkMan;
        postData.mobile = that.data.curAddressData.mobile;
        postData.code = that.data.curAddressData.code;
        postData.launchGroup = that.data.launchGroup
        
        postData.groupName = that.data.groupName
      
      
        if(that.data.groupIndex.length > 0){

          let gi = that.data.groupIndex[0]

          let g = that.data.groups[gi]

          if (g){
          postData.groupId = g.id
          }
        }
        if(that.data.shareGroupId){
          postData.groupId = that.data.shareGroupId
        }
      }
    }
    that.deliveryFee()
    if (that.data.curCoupon) {
      postData.couponId = that.data.curCoupon.id;
    }
    if (!e) {
      postData.calculate = "true";
    }
    wx.showLoading({
      title: '',
    })

    WXAPI.orderCreate(postData)

    .then(function (res) {
      if (res.code != 0) {
        wx.showModal({
          title: '错误',
          content: res.msg,
          showCancel: false
        })
        return;
      }
      if (!e) {

      const showDistance = util.getShowDistance(res.data.distance)
      const wxPayAmount = util.sub(res.data.amountReal,that.data.account.balance)
        that.setData({
          totalScoreToPay: res.data.score,
          allGoodsNumber: res.data.goodsNumber,
          allGoodsPrice: res.data.amountTotle,
          allGoodsAndYunPrice: res.data.amountLogistics + res.data.amountTotle,
          yunPrice: res.data.amountLogistics,
          amountReal: res.data.amountReal,
          distance:res.data.distance,
          showDistance,
          wxPayAmount
        });
        that.checkServiceDistance()
        return;
      }else{
        that.clearShareGroup(false)
      }
      return that.processAfterCreateOrder(res)
    })
    .finally(() => {
      wx.hideLoading()
      // 再唤起微信支付的时候，有大约1s的弹窗动画过度，加上 1s 的延迟可以稳定防止重复下单
      setTimeout(() => {
        this.setData({
          submitLoding: false
        })
      }, 1000)
    })
  },
  async deliveryFee(){
    
    const groupId = this.data.joinGroupId

    const joinGroup = this.data.groupWay === 'joinGroup'
    if(joinGroup && groupId && this.data.groups){
      this.data.groups.forEach(v=>{
        if(v.id === groupId){
          this.setData({
            yunPrice:v.totalEstimateLogisticsFee,
            deliveryFeeEstimate:v.estimateLogisticsFee
            })
        }
      })
    }else{
      // 根据地址算运费
      this.setData({yunPrice:0,deliveryFeeEstimate:0})
    }
  },
  showDeliveryRule(event){
    Dialog.alert({
      context:this,
      title: '拼团配送费规则',
      message: '先支付全部运费，当拼成后，运费由所有人均摊，本次支付的运费扣除真实运费后钱退回账户余额',
    })
  },
  async processAfterCreateOrder(res) {
    const dataset = {
      id: res.data.id,
      money: res.data.amountReal
    }
   await wxpay.toPayTap(dataset)
    // 直接弹出支付，取消支付的话，去订单列表
    // const res1 = await WXAPI.userAmount(wx.getStorageSync('token'))
    // if (res1.code != 0) {
    //   wx.showToast({
    //     title: '无法获取用户资金信息',
    //     icon: 'none'
    //   })
    //   wx.redirectTo({
    //     url: "/pages/all-orders/index"
    //   });
    //   return
    // }
    // const money = util.sub(res.data.amountReal,res1.data.balance)
 
    // if (money <= 0) {
    //   const dataset = {
    //     id: res.data.id,
    //     money: res.data.amountReal
    //   }
    //  await wxpay.toPayTap(dataset)

    // } else {
    //   wxpay.wxpay('order', money, res.data.id, "/pages/all-orders/index");
    // }
  },
  async initShippingAddress() {
    const res = await WXAPI.defaultAddress(wx.getStorageSync('token'))
    if (res.code == 0) {
      const curAddressData = res.data
      
      this.setData({
        curAddressData,
      })
    
      await this.groupNearby();
     
      if(this.data.takeTime){
        this.createOrder();
      }
      await this.checkShareGroup();
    } else {
      this.setData({
        curAddressData: null
      });
    }
    
    // if(!this.data.joinGroupId && this.data.shareGroupId){
    //   this.setData({
    //     takeTime:'',
    //     diningTime:''
    //   });
    // }
  },
  async checkShareGroup(){
    const shareGroupId = wx.getStorageSync("groupId")

    if (shareGroupId){
      this.setData({shareGroupId})

      const res = await WXAPI.getGroupInfo(shareGroupId)

      if (res.code ===0){
        this.setData({joinGroupId:shareGroupId})
        const shareGroup = res.data
        const takeTime = shareGroup.takeTime
        const diningTime = shareGroup.showTakeTime
        const groupIndex = [0]
        this.setData({shareGroup,takeTime,diningTime,groupIndex})
        this.createOrder()
      }else{
        Dialog.alert({
          context:this,
          message: res.msg,
        })
        this.clearShareGroup(false)
      }
    }

  },
  processYunfei() {

    var goodsList = this.data.goodsList
    if (goodsList.length == 0) {
      return
    }
    const goodsJsonStr = []
    var isNeedLogistics = 0;

    let inviter_id = 0;
    let inviter_id_storge = wx.getStorageSync('referrer');
    if (inviter_id_storge) {
      inviter_id = inviter_id_storge;
    }
    for (let i = 0; i < goodsList.length; i++) {
      let carShopBean = goodsList[i];
      if (carShopBean.logistics || carShopBean.logisticsId) {
        isNeedLogistics = 1;
      }

      const _goodsJsonStr = {
        propertyChildIds: carShopBean.propertyChildIds
      }
      if (carShopBean.sku && carShopBean.sku.length > 0) {
        let propertyChildIds = ''
        carShopBean.sku.forEach(option => {
          propertyChildIds = propertyChildIds + ',' + option.optionId + ':' + option.optionValueId
        })
        _goodsJsonStr.propertyChildIds = propertyChildIds
      }
      if (carShopBean.additions && carShopBean.additions.length > 0) {
        let goodsAdditionList = []
        carShopBean.additions.forEach(option => {
          goodsAdditionList.push({
            pid: option.pid,
            id: option.id
          })
        })
        _goodsJsonStr.goodsAdditionList = goodsAdditionList
      }
      _goodsJsonStr.goodsId = carShopBean.goodsId
      _goodsJsonStr.number = carShopBean.number
      _goodsJsonStr.logisticsType = 0
      _goodsJsonStr.inviter_id = inviter_id
      goodsJsonStr.push(_goodsJsonStr)

    }
    this.setData({
      isNeedLogistics: isNeedLogistics,
      goodsJsonStr:goodsJsonStr
    });

    // 没有选择时间的时候不计算运费
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/ad/index"
    })
  },
  checkServiceDistance(){
   if( this.data.shopInfo.serviceDistance * 1000 < this.data.distance){
        wx.showToast({
          title: '超出配送范围',
          icon:'error'
        })
   }
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/ad/index"
    })
  },
  bindChangeCoupon: function (e) {
    const selIndex = e.detail.value;
    this.setData({
      curCoupon: this.data.coupons[selIndex],
      curCouponShowText: this.data.coupons[selIndex].nameExt
    })
    this.createOrder()
  },
  radioChange (e) {
    this.setData({
      peisongType: e.detail.value
    })
    if(this.data.curAddressData){
      this.processYunfei()
    }
  },
  cancelLogin() {
    wx.navigateBack()
  },
  async getPhoneNumber(e) {
    if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        title: e.detail.errMsg,
        icon: 'none'
      })
      return;
    }
    const res = await WXAPI.bindMobileWxapp( this.data.code, e.detail.encryptedData, e.detail.iv)
    AUTH.wxaCode().then(code => {
      this.data.code = code
    })
    if (res.code === 10002) {
      wx.showToast({
        title: '请先登陆',
        icon: 'none'
      })
      return
    }
    if (res.code == 0) {
      wx.showToast({
        title: '读取成功',
        icon: 'success'
      })
      this.setData({
        mobile: res.data
      })
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  },
  async getUserApiInfo() {
    const res = await WXAPI.userDetail(wx.getStorageSync('token'))
    if (res.code == 0) {
      this.setData({
        nickname: res.data.base.nickname,
        avatarUrl: res.data.base.avatarUrl,
        mobile: res.data.base.mobile
      })
    }
  },
  diningTimeShow() {
    if(!this.data.groupIndex.length){
       if(!this.data.curAddressData){
      wx.showToast({
        title: '请先选择配送地址',
        icon:'error'
      })
      return ;
    }
      this.initMinPickTime()
      this.setData({
        diningTimeShow: true
      })
    }

  },
  diningTimeHide() {
    this.setData({
      diningTimeShow: false
    })
  },
  diningTimeConfirm(e) {
    let day = util.dateFormat("yyyy-MM-dd")
    this.setData({
      diningTime: e.detail,
      takeTime: day + ' ' + e.detail
    })
    this.diningTimeHide()
 
  },
  updateUserInfo(e) {
    wx.getUserProfile({
      lang: 'zh_CN',
      desc: '用于完善会员资料',
      success: res => {

        this._updateUserInfo(res.userInfo)
      },
      fail: err => {
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },
  async _updateUserInfo(userInfo) {
    const postData = {
      token: wx.getStorageSync('token'),
      nickname: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      city: userInfo.city,
      province: userInfo.province,
      gender: userInfo.gender,
    }
    const res = await WXAPI.modifyUserInfo(postData)
    if (res.code != 0) {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
      return
    }
    wx.showToast({
      title: '登陆成功',
    })
    this.getUserApiInfo()
  },
  detail (event){
    const index = event.target.dataset.index
  
    if(index === undefined){
      return 
    }
    const group = this.data.groups[index];

    wx.navigateTo({
      url:"/pages/group-detail/index?id="+ group.id
    })
  }
})